package com.sk.sourcecircle.activity.home.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.fragment.SearchAllFragment;
import com.sk.sourcecircle.activity.home.fragment.SearchHotFragment;
import com.sk.sourcecircle.activity.home.fragment.SearchNewFragment;
import com.sk.sourcecircle.activity.home.fragment.SearchRoundFragment;
import com.sk.sourcecircle.adapter.HisAdapter;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.entity.HotSearchBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.SPUtils;
import com.sk.sourcecircle.view.FlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/19.
 */

public class SearchActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, HandleDataCallBack {
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.my_pager)
    ViewPager myPager;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.hot_ll)
    FlowLayout hotLl;
    @BindView(R.id.null_ll)
    LinearLayout nullLl;
    @BindView(R.id.ed_search)
    EditText edSearch;

    SearchAllFragment searchAllFragment;
    SearchNewFragment searchNewFragment;
    SearchHotFragment searchHotFragment;
    SearchRoundFragment searchRoundFragment;
    @BindView(R.id.search_his)
    RecyclerView searchHis;

    private List<String> strings = new ArrayList<>();
    private List<String> his = new ArrayList<>();

    private List<Fragment> fragmentList = new ArrayList<>();
    private HisAdapter adapter;

    @Override
    protected int getContentView() {
        return R.layout.activity_search;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initHisory();

        initFragments();

        edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (edSearch.getText().toString().length() > 0) {

                        if (SPUtils.contains(mContext, "history")) {
                            String json = (String) SPUtils.get(mContext, "history", "");
                            List<String> stringList;
                            if (json != null) {
                                stringList = JSON.parseArray(json, String.class);
                            } else {
                                stringList = new ArrayList<>();
                            }
                            stringList.add(0, edSearch.getText().toString());
                            strings.addAll(stringList);
                            SPUtils.put(mContext, "history", JSON.toJSONString(strings));
                        } else {
                            strings.add(edSearch.getText().toString());
                            SPUtils.put(mContext, "history", JSON.toJSONString(strings));
                        }
                        nullLl.setVisibility(View.GONE);
                        searchLl.setVisibility(View.VISIBLE);
                        searchAllFragment.doSearch(edSearch.getText().toString());
                        searchNewFragment.doSearch(edSearch.getText().toString());
                        searchHotFragment.doSearch(edSearch.getText().toString());
                        searchRoundFragment.doSearch(edSearch.getText().toString());
                    } else {
                        Toast.makeText(mContext, "搜索条件不能为空!", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });

        AppApi.getHotSearch(this,0,this);
    }

    private void initHisory() {
        if (SPUtils.contains(mContext, "history")) {
            String json = (String) SPUtils.get(mContext, "history", "");
            List<String> stringList = JSON.parseArray(json, String.class);
            his.addAll(stringList);
        }

        searchHis.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new HisAdapter(R.layout.item_search_his, his);
        searchHis.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemChildClickListener(this);

    }

    private void initFragments() {

        searchAllFragment = new SearchAllFragment();
        searchNewFragment = new SearchNewFragment();
        searchHotFragment = new SearchHotFragment();
        searchRoundFragment = new SearchRoundFragment();

        fragmentList.add(searchAllFragment);
        fragmentList.add(searchNewFragment);
        fragmentList.add(searchHotFragment);
        fragmentList.add(searchRoundFragment);

        myPager.setOffscreenPageLimit(4);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.search_array), fragmentList);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);
    }

    @OnClick(R.id.cancel)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        his.remove(position);
        adapter.notifyItemRemoved(position);
        if (his.size() > 0) {
            SPUtils.put(mContext, "history", JSON.toJSONString(his));
        } else {
            SPUtils.remove(mContext, "history");
        }

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        String string = his.get(position);
        his.remove(position);
        his.add(0,string);

        SPUtils.put(mContext, "history", JSON.toJSONString(his));

        nullLl.setVisibility(View.GONE);
        searchLl.setVisibility(View.VISIBLE);
        searchAllFragment.doSearch(edSearch.getText().toString());
        searchNewFragment.doSearch(edSearch.getText().toString());
        searchHotFragment.doSearch(edSearch.getText().toString());
        searchRoundFragment.doSearch(edSearch.getText().toString());
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        HotSearchBean hotSearchBean = JSON.parseObject(result,HotSearchBean.class);
        List<String> stringList = hotSearchBean.getData();
        for(final String s:stringList){
            View view = getLayoutInflater().inflate(R.layout.item_hot_search,hotLl,false);
            final TextView textView = view.findViewById(R.id.tv_city);
            textView.setText(s);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (SPUtils.contains(mContext, "history")) {
                        String json = (String) SPUtils.get(mContext, "history", "");
                        List<String> stringList;
                        if (json != null) {
                            stringList = JSON.parseArray(json, String.class);
                        } else {
                            stringList = new ArrayList<>();
                        }
                        stringList.add(0, s);
                        strings.addAll(stringList);
                        SPUtils.put(mContext, "history", JSON.toJSONString(strings));
                    } else {
                        strings.add(s);
                        SPUtils.put(mContext, "history", JSON.toJSONString(strings));
                    }

                    nullLl.setVisibility(View.GONE);
                    searchLl.setVisibility(View.VISIBLE);
                    searchAllFragment.doSearch(s);
                    searchNewFragment.doSearch(s);
                    searchHotFragment.doSearch(s);
                    searchRoundFragment.doSearch(s);
                }
            });
            hotLl.addView(view);
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {

    }

    @Override
    public void handleErrorData(String error, int tag) {

    }
}
